﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using ZX.DAL.DBExtend;
using System.Configuration;

namespace ZX.WebApp.EHR
{
    /// <summary>
    /// WebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消对下行的注释。
    // [System.Web.Script.Services.ScriptService]
    public class WebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World WebService1q";
        }

        #region 读取截止指定的入职日期平台员工信息表，传给考勤平台同步
        /// <summary>
        /// 读取截止指定的入职日期平台员工信息表，传给考勤平台同步
        /// </summary>
        /// <param name="FrmJoinDate">入职日期开始</param>
        /// <param name="FrmJoinDate">入职日期结束</param>
        /// <returns></returns>
        [WebMethod]
        public DataTable GetEmpInfoByJoinDate(DateTime FrmJoinDate,DateTime ToJoinDate)
        {
            DataTable dt = new DataTable();
            DbSql dbsql = new DbSql();
            try
            {
                string sql = @"select ID,EmployeeCode,CName,Gender,JoinDate from hrEmployee 
                                where EmployeeCode is not null and CName is not null
                                and DepartmentID is not null and PostID is not null
                                and JoinDate>='{0}' and JoinDate<='{1}'
                                order by CName";
                dt = dbsql.ExecuteQuery(string.Format(sql, FrmJoinDate,ToJoinDate));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return dt;
        }
        #endregion

        #region 读取员工信息,根据员工去掉前缀后的5位数字工号
        /// <summary>
        /// 读取员工信息,根据员工去掉前缀后的5位数字工号
        /// </summary>
        /// <param name="employeeCode">员工工号,去掉前缀后的5位数字工号</param>
        /// <returns></returns>
        [WebMethod]
        public DataTable GetEmpInfoByCode(string employeeCode)
        {
            DataTable dt = new DataTable();
            DbSql dbsql = new DbSql();
            try
            {
                string sql = @"select top 1 ID,EmployeeCode,CName,Gender,JoinDate from hrEmployee 
                                where EmployeeCode is not null and CName is not null
                                and DepartmentID is not null and PostID is not null
                                and SUBSTRING(EmployeeCode,3,10)='{0}'
                                and SUBSTRING(EmployeeCode,3,10) !=''
                                order by CName";
                dt = dbsql.ExecuteQuery(string.Format(sql, employeeCode));
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return dt;
        }
        #endregion

        #region 从考勤系统导入打卡数据到平台
        /// <summary>
        /// 从考勤系统导入打卡数据到平台
        /// </summary>
        /// <param name="dtCardData">考勤系统打卡数据</param>
        /// <param name="succeedCount">成功的</param>
        /// <param name="existentCount">已经存在的</param>
        /// <param name="failedCount">失败的,工号不存在的</param>
        /// <param name="logMsg">返回平台不存在的工号</param>
        /// <returns></returns>
        [WebMethod]
        public void ImportCardData(DataTable dtCardData, ref int succeedCount, ref int existentCount, ref int failedCount, ref string logMsg)
        {
            //int succeedCount = 0, failedCount = 0, existentCount=0;
            List<string> lstNoExists = new List<string>();
            DbSql dbsql = new DbSql();
            try
            {
                string empName = "", employeeID = "", employeeCode = "", cardTime = "", machineNO = "", isRejigger = "N";
                string cardDate = DateTime.Now.ToString("yyyy-MM-dd");
                string sql = "";
                DataTable dt = new DataTable();
                foreach (DataRow dr in dtCardData.Rows)
                {
                    employeeCode = dr["CardNo"].ToString().Trim(); //考勤平台五位数字工号
                    empName = dr["EmplName"].ToString().Trim();//考勤平台员工姓名
                    dt = GetEmpInfoByCode(employeeCode);
                    if (dt.Rows.Count > 0)
                    {
                        employeeID = dt.Rows[0]["ID"].ToString();
                        employeeCode = dt.Rows[0]["EmployeeCode"].ToString();//平台有前缀工号
                        empName = dt.Rows[0]["CName"].ToString();
                        cardDate = dr["RecDate"].ToString();
                        cardTime = dr["RecTime"].ToString();
                        machineNO = dr["EquNo"].ToString();
                        isRejigger = "N";
                        sql = @"Insert into wkCardData([ID],[txtEmployeeID],[EmployeeID],[EmployeeCode],[CardDate],[CardTime],[MachineNO],[IsRejigger]) 
                                Values(NEWID(),'{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
                        sql = string.Format(sql, empName, employeeID, employeeCode, cardDate, cardTime, machineNO, isRejigger);
                        if (!IsExistsCardData(employeeID, cardDate, cardTime))
                        {
                            if (dbsql.ExecuteSql(sql) > 0)
                            {
                                succeedCount++;
                            }
                        }
                        else
                        {
                            existentCount++;
                        }
                    }
                    else
                    {
                        if (!lstNoExists.Contains(employeeCode))
                        {
                            lstNoExists.Add(employeeCode);
                            logMsg += string.Format("{0}【{1}】,", empName, employeeCode);
                            failedCount++;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 从考勤系统导入打卡数据到平台，一条导入
        /// <summary>
        /// 从考勤系统导入打卡数据到平台，一条导入
        /// </summary>
        /// <param name="cardNo"></param>
        /// <param name="recDate"></param>
        /// <param name="recTime"></param>
        /// <param name="equNo"></param>
        /// <param name="flag">未导入的原因，返回标志：1-工号不存在，2-打卡数据已经存在，3-其他错误</param>
        /// <returns></returns>
        [WebMethod]
        public bool ImportOneCardData(string cardNo, string recDate, string recTime, string equNo,ref string flag)
        {
            bool isOk = false;
            DbSql dbsql = new DbSql();
            try
            {
                string empName = "", employeeID = "", employeeCode = "", cardTime = "", machineNO = "", isRejigger = "N";
                string cardDate = DateTime.Now.ToString("yyyy-MM-dd");
                string sql = @"Insert into wkCardData([ID],[txtEmployeeID],[EmployeeID],[EmployeeCode],[CardDate],[CardTime],[MachineNO],[IsRejigger]) 
                                Values(NEWID(),'{0}','{1}','{2}','{3}','{4}','{5}','{6}')";
                DataTable dt = new DataTable();
                employeeCode = cardNo.Trim(); //考勤平台五位数字工号
                dt = GetEmpInfoByCode(employeeCode);
                if (dt.Rows.Count > 0)
                {
                    employeeID = dt.Rows[0]["ID"].ToString();
                    employeeCode = dt.Rows[0]["EmployeeCode"].ToString();//平台有前缀工号
                    empName = dt.Rows[0]["CName"].ToString();
                    cardDate = recDate.Trim();
                    cardTime = recTime.Trim();
                    machineNO = equNo.Trim();
                    isRejigger = "N";
                    sql = string.Format(sql, empName, employeeID, employeeCode, cardDate, cardTime, machineNO, isRejigger);
                    if (!IsExistsCardData(employeeID, cardDate, cardTime))
                    {
                        isOk = dbsql.ExecuteSql(sql) > 0;
                    }
                    else
                    {
                        flag = "2"; //打卡数据已经存在
                    }
                }
                else
                {
                    flag = "1"; //工号不存在
                }
            }
            catch (Exception ex)
            {
                flag = "3"; //其他错误
                throw ex;
            } 
            return isOk;
        }
        #endregion

        #region 原始打卡数据是否已经存在了
        /// <summary>
        /// 原始打卡数据是否已经存在了
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="cardDate"></param>
        /// <param name="cardTime"></param>
        /// <returns></returns>
        [WebMethod]
        public bool IsExistsCardData(string employeeId, string cardDate, string cardTime)
        {
            bool r = false;
            DbSql dbsql = new DbSql();
            try
            {
                string sql = "select top 1 EmployeeID from wkCardData where EmployeeID='{0}' and CardDate='{1}' and CardTime ='{2}'";
                sql = string.Format(sql, employeeId, cardDate, cardTime);
                r = dbsql.ExecuteQuery(sql).Rows.Count > 0;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return r;
        }
        #endregion

        #region 获取数据库链接
        /// <summary>
        /// 获取数据库链接
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public string GetConnectionString()
        {
            return ConfigurationManager.AppSettings["ConnectionString"];
        }
        #endregion
    }
}
